package com.skywolf.chem.manager.controller;

import com.skywolf.chem.common.excel.CellDefine;
import com.skywolf.chem.common.excel.ExcelTable;
import com.skywolf.chem.common.excel.ExcelWriter;
import com.skywolf.chem.common.sysconfig.pojo.vo.PageVO;
import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.common.sysconfig.utils.IpUtils;
import com.skywolf.chem.manager.entity.*;
import com.skywolf.chem.manager.service.ActivityService;
import com.skywolf.chem.match.entity.GroupInfo;
import com.skywolf.chem.match.entity.Type;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pei_pei on 2021/9/26.
 */
@Slf4j
@RestController
@RequestMapping("/manager/activity")
@Api(value = "管理端-活动相关", description = "管理端-活动相关")
public class ActivityManagerController {
    private static final Logger logger = LoggerFactory.getLogger(IpUtils.class);

    @Autowired
    ActivityService activityService;

    @ApiOperation(value = "获取活动列表",notes = "获取活动列表")
    @RequestMapping(value = "/getActivityList",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<ActivityVo> getActivityList(@RequestBody @Validated ActivityParam queryParam) {
        PageVO<ActivityVo> page = activityService.getActivityList(queryParam);
        return RespData.success(page);
    }

//    @ApiOperation(value = "删除活动-下架",notes = "删除活动-下架")
//    @RequestMapping(value = "/delActivity",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    public RespData<String> delActivity(@RequestParam(value = "id",required = true) Long id) {
//        activityService.delActivity(id);
//        return RespData.success();
//    }

    @ApiOperation(value = "审核活动",notes = "审核活动")
    @RequestMapping(value = "/ApplyActivity",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> ApplyActivity(@RequestBody @Validated ActivityApplyRequest request) {
        activityService.applyActivity(request);
        return RespData.success();
    }

    @ApiOperation(value = "获取活动类型列表",notes = "获取活动类型列表")
    @RequestMapping(value = "/getTypeList",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<Type> getActivityTypeList() {
        List<Type> list = activityService.getActivityTypeList();
        return RespData.success(list);
    }

    @ApiOperation(value = "添加或编辑活动详情",notes = "添加或编辑活动详情-传入了info中ID参数就是更新，更新那个字段，就给那个字段传参，不更新的字段不提交")
    @RequestMapping(value = "/addActivity",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> addActivity(@RequestBody @Validated ActivityRequest request) {
        try{
            if(request==null || request.getInfo()==null){
                return RespData.error("参数错误");
            }
            if(!request.getInfo().getApplyStartTime().isBefore(request.getInfo().getApplyEndTime())){
                return RespData.error("报名开始时间要早余结束时间");
            }
            if(!request.getInfo().getMatchStartTime().isBefore(request.getInfo().getMatchEndTime())){
                return RespData.error("比赛开始时间要早余结束时间");
            }
            if(!request.getInfo().getApplyStartTime().isBefore(request.getInfo().getMatchStartTime())){
                return RespData.error("报名开始时间要在比赛开始时间之前");
            }
            if(request.getGroupInfo()!=null && request.getGroupInfo().size()>0){
                List<GroupInfo> groupInfo = request.getGroupInfo();
                for (int i=0;i<groupInfo.size();i++){
                    GroupInfo item = groupInfo.get(i);
                    if(!item.getMatchStartTime().isBefore(item.getMatchEndTime())){
                        return RespData.error("小组比赛开始时间要早余结束时间");
                    }
                }
            }
            request.getInfo().setApplyStatus(null);
            request.getInfo().setMatchStatus(100);
            activityService.addActivity(request);
            return RespData.success();
        }catch (Exception e){
            logger.error("addActivity error:{}",e);
            return RespData.error("服务异常，请稍后再试");
        }
    }

    @ApiOperation(value = "获取活动详情",notes = "获取活动详情")
    @RequestMapping(value = "/getActivityInfo",method = {RequestMethod.POST,RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<ActivityRequest> getActivityInfo(@RequestParam(value = "id",required = true) Long id) {
        try{
            if(id==null){
                return RespData.error("请选择要查询的活动");
            }
            ActivityRequest result = activityService.getActivityInfo(id);
            return RespData.success(result);
        }catch (Exception e){
            logger.error("addActivity error:{}",e);
            return RespData.error("服务异常，请稍后再试");
        }
    }


    @ApiOperation(value = "报名列表", notes = "报名列表")
    @RequestMapping(value = "/getUserList",method = {RequestMethod.POST,RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<PageVO<ActivityRecordVo>> getUserList(@RequestBody @Validated ActivityRecordRequest queryParam) {
        PageVO<ActivityRecordVo> pageVo= activityService.getUserList(queryParam);
        return RespData.success(pageVo);
    }


    @ApiOperation(value = "报名用户审核",notes = "报名用户审核")
    @RequestMapping(value = "/ApplyActivityUser",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> ApplyActivityUser(@RequestBody @Validated ActivityApplyUserRequest request) {
        activityService.applyActivityUser(request);
        return RespData.success();
    }

    @ApiOperation(value = "报名人详情",notes = "报名人详情-传入报名ID")
    @RequestMapping(value = "/getActivityUserInfo",method = {RequestMethod.POST,RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<ActivityUserInfoResponse> getActivityUserInfo(@RequestParam(value = "id",required = true) Long id) {
        try{
            if(id==null){
                return RespData.error("请选择报名ID");
            }
            ActivityUserInfoResponse result = activityService.getActivityUserInfo(id);
            return RespData.success(result);
        }catch (Exception e){
            logger.error("addActivity error:{}",e);
            return RespData.error("服务异常，请稍后再试");
        }
    }

    @ApiOperation(value = "导出报名列表",notes = "导出报名列表")
    @RequestMapping(value = "reportData", method = RequestMethod.GET)
    public ResponseEntity<byte[]> reportData(@RequestParam(value = "activityName",required = true) String activityName) throws Exception{
        List<ReportUserListVo> pageVo= activityService.getReportUserList(activityName);
        Map<String,Object> exportObject = new HashMap<>();
        Map<String,Collection<CellDefine>> exportColumns = new HashMap<>();
        exportObject.put("报名列表",pageVo);
        exportColumns.put("报名列表",ReportUserListVo.columns);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        ExcelWriter.writeMulti(exportColumns, exportObject, ExcelTable.ExcelType.XLSX, buf);
        HttpHeaders headers = new HttpHeaders();
        String filename = "report_activity_list.xlsx";
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", new String(filename.getBytes("UTF-8"), "ISO8859-1"));
        return new ResponseEntity<>(buf.toByteArray(), headers, HttpStatus.OK);
    }


    @ApiOperation(value = "获取活动类型列表-test",notes = "获取活动类型列表-test")
    @RequestMapping(value = "/getTypeListtest",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<Type> getTypeListtest() {
        List<Type> list = activityService.getActivityTypeListTest();
        return RespData.success(list);
    }
}
